package com.bsoft.gol.hcb.service;

import com.alibaba.fastjson.JSON;
import com.bsoft.gol.hcb.bean.request.HealthRecordsListReq;
import com.bsoft.gol.hcb.bean.response.HealthRecordsListResp;
import com.bsoft.gol.hcb.utils.CommonUtils;
import com.google.common.collect.Lists;
import ctd.controller.exception.ControllerException;
import ctd.dictionary.controller.DictionaryController;
import ctd.net.rpc.Client;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.JSONUtils;
import ctd.util.annotation.RpcService;
import hcn.base.Organization;
import hcn.util.BaseResponse;
import hcn.util.ResultCode;
import hcn.util.RpcUserToken;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.atag.util.common.CopyUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import service.rpc.BaseUserManageUnitIntf;
import service.rpc.FollowUpIndexService;
import service.rpc.OrganizationInfoIntf;
import service.rpc.ServiceOpenIntf;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Description
 * @Author:FangZhiyi
 * @Data Created in 2019/6/17 14:03
 * @Moddified By:
 */
@SsdevService("healthRecordsService")
public class HealthRecordsService {
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(HealthRecordsService.class);

    @Value("${healthRecord_organization_id}")
    private String organizationId;

    @Autowired
    private OrganizationInfoIntf organizationInfoService;

    @Autowired
    private BaseUserManageUnitIntf baseUserManageUnitService;

    @Autowired
    OdsVisitMedicalDAO odsVisitMedicalDAO;

    @Autowired
    private FollowUpIndexService followUpIndexService;

    @Autowired
    private ServiceOpenIntf serviceOpenService;
    /**
     * @Description 获取健康记录列表 XML格式
     */
    @RpcService

    public List<HealthRecordsListResp> healthRecordsList(HealthRecordsListReq request) throws ControllerException {
        if (StringUtils.isNotEmpty(request.getEndTime())) {
            request.setEndTime(request.getEndTime() + " 23:59:59");
        }
        if (StringUtils.isNotEmpty(request.getStartTime())) {
            request.setStartTime(request.getStartTime() + " 00:00:00");
        }
        List<HealthRecordsListResp> healthRecordsListRespList = new ArrayList<>();
        //若是机构代码为空，代表这个请求时GOL发起的，需要使用参数配置
        if (CommonUtils.isEmpty(request.getHospitalCode())) {
            request.setHospitalCode(organizationId);
        }

        Organization organization = organizationInfoService.getOrgDetailByOrgCode(request.getHospitalCode());
        if (null != organization) {
            request.setInternetOutpatientType(organization.getInternetOutpatientType());
        }
        try {
            BaseResponse<List<hcn.cmc.bean.response.HealthRecordsListResp>> tmp = (BaseResponse<List<hcn.cmc.bean.response.HealthRecordsListResp>>) Client.rpcInvoke(
                    "hcnInterface.healthRecordsService", "healthRecordsListXML", CopyUtils.copy(request, hcn.cmc.bean.request.HealthRecordsListReq.class));
            if (tmp == null || ResultCode.SUCCESS != tmp.getCode()) {
                return healthRecordsListRespList;
            }
            if (CommonUtils.isEmpty(tmp.getData())) {
                return healthRecordsListRespList;
            }
            healthRecordsListRespList = JSON.parseArray(JSONUtils.writeValueAsString(tmp.getData()), HealthRecordsListResp.class);
            healthRecordsListRespList.forEach(e -> {e.setPatientSexText(getGenderDicText(e.getPatientSex()));});
        } catch (Exception e) {
            log.error("healthRecordsList error:", e);
            return healthRecordsListRespList;
        }

        //获取就诊人身份证号码和手机号码和患者用户Id
        if (CommonUtils.isEmpty(healthRecordsListRespList)) {
            return healthRecordsListRespList;
        }

        List<String> patientCodes = healthRecordsListRespList.stream().map(h -> h.getPatientCode()).collect(Collectors.toList());
        Map<String, Map<String, String>> userByPatientCodes = baseUserManageUnitService.findUserByPatientCodes(organization.getOrgId(), patientCodes);

        // 机构是否开通专科随访
        Boolean serviceFlag = null;
        try {
            serviceFlag = serviceOpenService.getServiceByOrgId(RpcUserToken.getTenantId(), "0131",
                    organization.getOrgId());
        } catch (Exception e) {
            log.error("查询机构开通专访权限失败");
        }

        //管辖权限标志：0 无权限 1 有权限
        Integer authFlag = serviceFlag ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO;

        for (HealthRecordsListResp recordsListResp : healthRecordsListRespList) {
            recordsListResp.setOrgId(organization.getOrgId());
            if (CommonUtils.isNotEmpty(userByPatientCodes)) {
                Map<String, String> patientMap = userByPatientCodes.get(recordsListResp.getPatientCode());
                if (CommonUtils.isNotEmpty(patientMap)) {
                    recordsListResp.setPatientUserId(CommonUtils.isEmpty(patientMap.get("masterUserId")) ? "" : patientMap.get("masterUserId"));
                    recordsListResp.setIdentityNumber(CommonUtils.isEmpty(patientMap.get("idCard")) ? "" : patientMap.get("idCard"));
                    recordsListResp.setPhoneNumber(CommonUtils.isEmpty(patientMap.get("phoneNo")) ? "" : patientMap.get("phoneNo"));
                    recordsListResp.setConsultMpiId(CommonUtils.isEmpty(patientMap.get("mpiId")) ? "" : patientMap.get("mpiId"));
                }

                // 管辖权限标志：0 无权限 1 有权限
                recordsListResp.setAuthFlag(authFlag);

                if(NumberUtils.INTEGER_ONE == authFlag){
                    try {
                        // 阅读标志：0未读 1已读
                        List<Long> teamIdList = Lists.newArrayList();
                        List<Long> medicalTeamIdLis = Lists.newArrayList();
                        if (CommonUtils.isNotEmpty(patientMap)) {
                            teamIdList = followUpIndexService.queryTeamIdListByCardAndDocId(String.valueOf(patientMap.get("idCardType")),
                                    String.valueOf(patientMap.get("idCard")), recordsListResp.getDoctorCode());
                            medicalTeamIdLis = followUpIndexService.queryMedicalTeamIdListByCardAndDocId(String.valueOf(patientMap.get("idCardType")),
                                    String.valueOf(patientMap.get("idCard")), recordsListResp.getDoctorCode());
                        }
                        //入组记录id列表
                        recordsListResp.setTeamChronicGroupIdList(teamIdList);
                        // 阅读标志：0未读 1已读
                        Integer reminderNum = followUpIndexService.findDoctorReminderByPatientId(recordsListResp.getDoctorCode(), medicalTeamIdLis);
                        recordsListResp.setReadFlag(reminderNum > 0 ? NumberUtils.INTEGER_ZERO : NumberUtils.INTEGER_ONE);
                    } catch (Exception e) {
                        log.error("查询阅读标识失败：" + e);
                    }
                }

            }

            // 调试代码--todo
            if ("4276".equals(recordsListResp.getPatientCode())) {
                recordsListResp.setIsAllergy("1");
                recordsListResp.setAllergyCondition("牛奶、鸡蛋，头孢过敏");
                // 药物过敏
                HealthRecordsListResp.Allergy medicalAllergy = new HealthRecordsListResp.Allergy();
                medicalAllergy.setAllergenicIngredientsCode("aaa");
                medicalAllergy.setAllergenicIngredients("头孢过敏");
                medicalAllergy.setAllergicSymptoms("皮试阳性");
                medicalAllergy.setAllergySeverity("一般过敏");
                medicalAllergy.setAllergyType("青霉素类");
                // 其他过敏
                HealthRecordsListResp.Allergy otherAllergy = new HealthRecordsListResp.Allergy();
                otherAllergy.setAllergenicIngredientsCode("bbb");
                otherAllergy.setAllergenicIngredients("牛奶、鸡蛋");
                otherAllergy.setAllergicSymptoms("症状。。");
                otherAllergy.setAllergySeverity("一般过敏");
                otherAllergy.setAllergyType("食物类");
                recordsListResp.setMedicalAllergyList(Arrays.asList(medicalAllergy));
                recordsListResp.setOtherAllergyList(Arrays.asList(otherAllergy));
            }
            // 调试代码--todo

        }
        //通过VisitId查询直接进详情，则不过滤门诊还是互联网诊疗
        if (StringUtils.isNotEmpty(request.getVisitId())) {
            return healthRecordsListRespList;
        }

        //线下门诊代码
        String outpatientType = organization.getOutpatientType() == null ? "111" : organization.getOutpatientType();
        //线上挂号类型代码
        String internetOutpatientType = organization.getInternetOutpatientType() == null ? "114" : organization.getInternetOutpatientType();

        //过滤门诊的
        if (1 == request.getType() && CommonUtils.isNotEmpty(healthRecordsListRespList)) {
            List<HealthRecordsListResp> list = healthRecordsListRespList.stream().filter(item -> outpatientType.equals(item.getOutpatientType())).collect(Collectors.toList());
            return list;
        } else if (2 == request.getType() && CommonUtils.isNotEmpty(healthRecordsListRespList)) {
            List<HealthRecordsListResp> list = healthRecordsListRespList.stream().filter(item -> internetOutpatientType.equals(item.getOutpatientType())).collect(Collectors.toList());
            return list;
        }
        healthRecordsListRespList = healthRecordsListRespList.stream().filter(item -> StringUtils.isNotEmpty(item.getDateOfConsultation())).collect(Collectors.toList());
        return healthRecordsListRespList;
    }

//    /**
//     * @Description 获取病历模板 XML格式
//     */
//    @RpcService
//    public BaseResponse<List<SyncTemplateResp>> SyncTemplateList(SyncTemplateReq request) {
//        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(request));
//        String url = Constants.COMMON_PROXY_URL + Constants.SYNCTEMPLATE_LIST;
//        JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(url, jsonParams);
//        log.info("SyncTemplateList==jsonObject===" + jsonObject.toJSONString());
////        String a = "{\"code\":200,\"data\":[{\"templateClassList\":[{\"templateClassId\":\"15\",\"templateClassName\":\"住院病历\"},{\"templateClassId\":\"16\",\"templateClassName\":\"再次住院病历\"},{\"templateClassId\":\"2000239\",\"templateClassName\":\"阶段小结\"},{\"templateClassId\":\"2000240\",\"templateClassName\":\"专科病历\"}],\"hospitalName\":\"\",\"medicalClassName\":\"住院病历类\",\"medicalClassId\":\"14\",\"hospitalCode\":\"\"},{\"templateClassList\":[{\"templateClassId\":\"11\",\"templateClassName\":\"入院记录\"},{\"templateClassId\":\"12\",\"templateClassName\":\"再次入院记录\"},{\"templateClassId\":\"2000198\",\"templateClassName\":\"接收记录\"}],\"hospitalName\":\"\",\"medicalClassName\":\"入院记录类\",\"medicalClassId\":\"292\",\"hospitalCode\":\"\"},{\"templateClassList\":[{\"templateClassId\":\"20\",\"templateClassName\":\"24小时内入院记录\"},{\"templateClassId\":\"21\",\"templateClassName\":\"24小时内入院死亡记录\"}],\"hospitalName\":\"\",\"medicalClassName\":\"24小时内记录类\",\"medicalClassId\":\"18\",\"hospitalCode\":\"\"},{\"templateClassList\":[{\"templateClassId\":\"295\",\"templateClassName\":\"首次病程记录\"},{\"templateClassId\":\"296\",\"templateClassName\":\"普通病程记录\"},{\"templateClassId\":\"2000188\",\"templateClassName\":\"科主任查房\"},{\"templateClassId\":\"2000192\",\"templateClassName\":\"科主任查房(不换页)\"},{\"templateClassId\":\"23\",\"templateClassName\":\"副主任医师查房记录\"},{\"templateClassId\":\"297\",\"templateClassName\":\"主任医师查房记录\"},{\"templateClassId\":\"25\",\"templateClassName\":\"主治医师查房记录\"},{\"templateClassId\":\"2000195\",\"templateClassName\":\"三级医师查房记录\"},{\"templateClassId\":\"30\",\"templateClassName\":\"转科记录\"},{\"templateClassId\":\"31\",\"templateClassName\":\"接收记录\"},{\"templateClassId\":\"28\",\"templateClassName\":\"交班记录\"},{\"templateClassId\":\"29\",\"templateClassName\":\"接班记录\"},{\"templateClassId\":\"27\",\"templateClassName\":\"抢救记录\"},{\"templateClassId\":\"26\",\"templateClassName\":\"阶段小结\"},{\"templateClassId\":\"33\",\"templateClassName\":\"多科会诊记录\"},{\"templateClassId\":\"82\",\"templateClassName\":\"术前小结\"},{\"templateClassId\":\"36\",\"templateClassName\":\"疑难病例讨论记录\"},{\"templateClassId\":\"54\",\"templateClassName\":\"术后病程记录\"}],\"hospitalName\":\"\",\"medicalClassName\":\"病程记录类\",\"medicalClassId\":\"294\",\"hospitalCode\":\"\"},{\"templateClassList\":[{\"templateClassId\":\"304\",\"templateClassName\":\"手术前病例讨论记录\"},{\"templateClassId\":\"38\",\"templateClassName\":\"手术前小结\"},{\"templateClassId\":\"1001\",\"templateClassName\":\"麻醉记录\"},{\"templateClassId\":\"40\",\"templateClassName\":\"麻醉前小结\"},{\"templateClassId\":\"306\",\"templateClassName\":\"手术记录\"},{\"templateClassId\":\"42\",\"templateClassName\":\"术后记录\"}],\"hospitalName\":\"\",\"medicalClassName\":\"手术麻醉类\",\"medicalClassId\":\"303\",\"hospitalCode\":\"\"},{\"templateClassList\":[],\"hospitalName\":\"\",\"medicalClassName\":\"出(转)院记录\",\"medicalClassId\":\"51\",\"hospitalCode\":\"\"},{\"templateClassList\":[{\"templateClassId\":\"290\",\"templateClassName\":\"死亡记录\"},{\"templateClassId\":\"291\",\"templateClassName\":\"死亡病例讨论记录\"}],\"hospitalName\":\"\",\"medicalClassName\":\"死亡记录类\",\"medicalClassId\":\"288\",\"hospitalCode\":\"\"},{\"templateClassList\":[],\"hospitalName\":\"\",\"medicalClassName\":\"讨论记录\",\"medicalClassId\":\"2000214\",\"hospitalCode\":\"\"},{\"templateClassList\":[{\"templateClassId\":\"58\",\"templateClassName\":\"手术同意书\"},{\"templateClassId\":\"59\",\"templateClassName\":\"输血治疗同意书\"},{\"templateClassId\":\"60\",\"templateClassName\":\"特殊治疗同意书\"},{\"templateClassId\":\"61\",\"templateClassName\":\"特殊检查同意书\"},{\"templateClassId\":\"62\",\"templateClassName\":\"授权委托书\"},{\"templateClassId\":\"81\",\"templateClassName\":\"谈话记录单\"}],\"hospitalName\":\"\",\"medicalClassName\":\"授权同意类\",\"medicalClassId\":\"329\",\"hospitalCode\":\"\"},{\"templateClassList\":[],\"hospitalName\":\"\",\"medicalClassName\":\"病危(重)通知类\",\"medicalClassId\":\"2000186\",\"hospitalCode\":\"\"},{\"templateClassList\":[],\"hospitalName\":\"\",\"medicalClassName\":\"其他类\",\"medicalClassId\":\"2000202\",\"hospitalCode\":\"\"},{\"templateClassList\":[],\"hospitalName\":\"\",\"medicalClassName\":\"会诊类\",\"medicalClassId\":\"2000203\",\"hospitalCode\":\"\"},{\"templateClassList\":[],\"hospitalName\":\"\",\"medicalClassName\":\"医患沟通类\",\"medicalClassId\":\"34\",\"hospitalCode\":\"\"},{\"templateClassList\":[{\"templateClassId\":\"69\",\"templateClassName\":\"X线检查申请单\"},{\"templateClassId\":\"70\",\"templateClassName\":\"CT检查申请单\"},{\"templateClassId\":\"72\",\"templateClassName\":\"MRI检查申请单\"}],\"hospitalName\":\"\",\"medicalClassName\":\"检查申请类\",\"medicalClassId\":\"66\",\"hospitalCode\":\"\"},{\"templateClassList\":[],\"hospitalName\":\"\",\"medicalClassName\":\"报告结果类\",\"medicalClassId\":\"67\",\"hospitalCode\":\"\"},{\"templateClassList\":[{\"templateClassId\":\"102\",\"templateClassName\":\"CHA评分评估表\"},{\"templateClassId\":\"17\",\"templateClassName\":\"中医体质辨识表\"},{\"templateClassId\":\"19\",\"templateClassName\":\"中医调理方案\"}],\"hospitalName\":\"\",\"medicalClassName\":\"评估评分表类\",\"medicalClassId\":\"79\",\"hospitalCode\":\"\"},{\"templateClassList\":[],\"hospitalName\":\"\",\"medicalClassName\":\"化疗记录类\",\"medicalClassId\":\"83\",\"hospitalCode\":\"\"},{\"templateClassList\":[{\"templateClassId\":\"107\",\"templateClassName\":\"CHA评估表使用说明\"}],\"hospitalName\":\"\",\"medicalClassName\":\"帮助类\",\"medicalClassId\":\"104\",\"hospitalCode\":\"\"}]}";
//        BaseResponse<List<SyncTemplateResp>> result = JSON.parseObject(jsonObject.toJSONString(), BaseResponse.class);
//        return result;
//    }

    /**
     * 病情描述查询
     *
     * @param visitId the visitId
     * @author Qulc - 2022/5/7 10:12
     */
    @RpcService
    public String queryDescription(String visitId) {
        String description = odsVisitMedicalDAO.getConditionDescription(visitId);
        return description;
    }


    private String getGenderDicText(String value){
        if(StringUtils.isBlank(value)){
            return "";
        }
        String text = "";
        try {
            ctd.dictionary.Dictionary dic = DictionaryController.instance().get("hcn.base.dictionary.gender");
            if(null != dic){
                text = dic.getText(value);
                if(StringUtils.isNotEmpty(text)){
                    return text;
                }
            }
        } catch (Throwable e) {

        }
        return "";
    }

}
